import java.net.*;
import java.util.*;

public class UdpGame {
    public static DatagramPacket packet = new DatagramPacket(new byte[1024], 1024);
    public static Scanner sc = new Scanner(System.in);

    static public void sendBroadcast(DatagramSocket sd, int port, String s) throws Exception {
        sd.setBroadcast(true);
        packet.setSocketAddress(new InetSocketAddress("255.255.255.255", port));
        packet.setData(s.getBytes());
        sd.send(packet);
        sd.setBroadcast(false);
    }

    static public DatagramSocket searchSrv(int port) throws Exception {
        DatagramSocket sd = new DatagramSocket();
        sendBroadcast(sd, port, "请求");
        sd.setSoTimeout(3000);
        try {
            sd.receive(packet);
        } catch (SocketTimeoutException e) {
            sd.close();
            return null;
        }
        sd.connect(packet.getSocketAddress());
        return sd;
    }

    public static DatagramSocket createSrv(int port) throws Exception {
        DatagramSocket sd = new DatagramSocket(null);
        sd.setReuseAddress(true);
        sd.bind(new InetSocketAddress(port));
        return sd;
    }

    static public DatagramSocket waitCli(DatagramSocket sd) throws Exception {
        String s = null;
        while (true) {
            sd.receive(packet);
            s = new String(packet.getData(), 0, packet.getLength());
            if (s.equals("请求")) {
                sd.close();
                sd = new DatagramSocket();
                sd.send(packet);
                break;
            }
        }
        return sd;
    }

    static public void main(String [] args) throws Exception {
        int port = 9183;
        String s = null;
        DatagramSocket sd = searchSrv(port);

        if (sd == null) {
            System.out.printf("本套接字作为服务器运行!\n");
            sd = waitCli(createSrv(port));

            while (true) {
                sd.receive(packet);
                s = new String(packet.getData(), 0, packet.getLength());
                System.out.printf("%s: %s\n", packet.getSocketAddress(), s);
                if (s.equals("quit")) {
                    break;
                }
            }
        } else {
            System.out.printf("本套接字作为客户端运行!\n");
            while (true) {
                System.out.printf("请输入发送数据: ");
                s = sc.nextLine();
                packet.setData(s.getBytes());
                sd.send(packet);
                if (s.equals("quit"))
                    break;
            }
        }
        sd.close();
    }
}
